package com.dayu.rabbitmq.simple;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

import org.springframework.core.serializer.DefaultDeserializer;

import com.dayu.rabbitmq.util.MQUtil;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;

/**
 * @author dayu
 * @date 2019/02/20 Describe
 */
public class GetMsg {

    private static String QUEUE_NAME = "test_queue_name";

    //新版本的使用方法
    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取一个连接
        Connection connection = MQUtil.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();

        // 创建队列声明, 如果队列存在，不影响
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
                throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String message = new String(body, "utf-8");
                System.out.println("----接收到：-----" + message + "," + LocalDateTime.now());
            }
        };
        
        // 监听队列
        channel.basicConsume(QUEUE_NAME, true, consumer);

    }

    /**
     * 老版本的使用方法
     */
    private static void oldMethod() {
        try {
            // 获取一个连接
            Connection connection = MQUtil.getConnection();
            // 从连接中获取一个通道
            Channel channel = connection.createChannel();

            // 创建队列声明, 如果队列存在，不影响
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            QueueingConsumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(QUEUE_NAME, true, consumer);
            while (true) {
                Delivery nextDelivery = consumer.nextDelivery();
                String msg = new String(nextDelivery.getBody());
                System.out.println("-----接收到消息------" + msg);
            }

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } catch (ShutdownSignalException e) {
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
